<template>
  <el-dialog custom-class="mater_dialog" v-model="materVisible" width="815px" @close="handleClose">
    <template #title>
      <div class="dialog_header">素材库选择</div>
    </template>

    <div class="tab_box">
      <div class="tab_header">
        <el-tabs v-model="baseId" class="base_tabs" @tab-click="tabClick">
          <el-tab-pane v-for="item in tabs" :key="item.id" :label="item.name" :name="item.id">
          </el-tab-pane>
        </el-tabs>
        <div class="tab_reset" @click="reset">刷新</div>
      </div>
      <div class="tab_content">
        <el-scrollbar class="group_box" v-if="baseId != 15">
          <Grouping @submit="getChildGroup" :treeData="treeData"></Grouping>
        </el-scrollbar>
        <div class="line" v-if="baseId != 15"></div>
        <div class="pane-box">
          <ToggleType v-if="baseId == 99 && types.includes(shopType)" v-model="toggleType" @select="selectToggleType" :isGoodsOnly="isGoodsOnly" />
          <SearchOfficialAccounts v-if="baseId == 15" v-model:title="officialAccountsParams.article_title" v-model:id="officialAccountsParams.official_account_id" @change="getList" />
          <el-input class="pane-box-input" v-else v-model="keyword" placeholder="搜索标题或文件名" type="text" :prefix-icon="Search" clearable @clear="clear" v-debounce="[getList]">
          </el-input>
          <div class="pane-body-box" :class="{'pane-body-box-ecommerce': baseId == 99 && types.includes(shopType)}">
            <keep-alive>
              <div :key="randomKey">
                <component v-if="tabItem?.comName" :multiple="multiple" :is="tabItem?.comName" @getData="getDataFun" :remainNum="remainNum" :baseList="baseList" :selectBaseList="selectBaseList" :totalNum="existFile" :infinite="infinite" />
                <component v-else :multiple="multiple" :is="toggleType === 0 ? tabItem?.GoodsList : tabItem?.PageList" @getData="getDataFun" :remainNum="remainNum" :baseList="baseList" :selectBaseList="selectBaseList" :totalNum="existFile" :infinite="infinite" />
              </div>
            </keep-alive>
          </div>
          <div :key="randomKey2">
            <ZWPagination v-if="tabItem?.comName" ref="PaginationRef1" @submit="getList" />
            <ZWPagination v-else-if="toggleType === 0" ref="PaginationRef2" @submit="getList" />
            <ZWPagination v-else-if="toggleType === 1" ref="PaginationRef3" @submit="getList" />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="footer_box">
        <div class="right_footer">
          <!-- 本地上传 -->
          <template v-if="localUploadisShow.includes(baseId) && !disableUploadisShow.includes(baseId)">
            <el-button plain v-if="baseId == 6" @click="showCreatLocalLink">创建链接</el-button>
            <ZWUpload v-else :upInfo="upInfo()" ref="ZWUploadRef" @submit="getUploadFile" />
          </template>
          <el-button v-else plain @click="handleClose">取消</el-button>
          <el-button class="ml20" type="primary" @click="submitHandel">保存</el-button>
        </div>
        <div class="left_footer" v-show="baseId != 1 && !infinite">
          已选择<span>{{ selectNum }}</span
          >{{ `${baseId == 2 ? '张' : '个'}` }}{{ selectNameStr }},您还可选<span>{{ remainNum }}</span
          >个素材
        </div>
      </div>
    </template>

  </el-dialog>

  <CreateLocalLink ref="CreateLocalLinkRef" @getLocalLink="getUploadFile" />
  <!-- 视频播放器 -->
  <VideoWicket ref="VideoWicketRef" />

</template>
<script lang="ts" setup>
  import { ref, reactive, watch, shallowRef, computed } from 'vue'
  import { useStore } from '@/store'
  import { Search } from '@element-plus/icons-vue'
  import { GetVideoList } from '@/api/media'
  import { getGroupList, getVoiceList, getImageList, linkList, getFileList, getTextList, getGroupMarket, getCollectList, getMaterialStoreList, getGoodsList, getPageList } from '@/api/concreation'
  import { activityList } from '@/api/smartMarketing/luckyDraw'
  import {getOfficialArticleList} from '@/api/content/channelFootage/officialaccountgraphics'
  import Grouping from './Grouping.vue'
  import ZWPagination from '@/components/ZWPagination.vue'

  import ImageList from './ImageList.vue'
  import VideoList from './VideoList.vue'
  import LinkList from './LinkList.vue'
  import FileList from './fileList.vue'
  import TextList from './TextList.vue'
  import AudioList from './audioList.vue'
  import CollectList from './CollectList.vue'
  import GoodsList from './GoodsList.vue'
  import PageList from './PageList.vue'
  import OfficialAccounts from './OfficialAccounts.vue'

  import LuckDraw from './luckDraw.vue'
  import CreateLocalLink from './CreateLocalLink.vue'
  import VideoWicket from './components/videoWicket.vue'
  
  import ZWUpload from './ZWUpload.vue'
  import ToggleType from './ToggleType.vue'

  import SearchOfficialAccounts from './components/SearchOfficialAccounts.vue'

  import { ElMessage } from 'element-plus'
  import { deepClone } from '@/utils/utils'
  const emit = defineEmits(['submit'])

  const PaginationRef1 = ref<any>();
  const PaginationRef2 = ref<any>();
  const PaginationRef3 = ref<any>();

  const store = useStore()
  const CreateLocalLinkRef = <any>ref(null)
  const showLuck = ref(false)
  const keyword = ref('')
  const materVisible = ref(false)
  const groupId = ref(0)
  const shopId = ref<number|string>('')
  const shopType = ref<number|string>('1')
  
  const baseId = ref<string|number>('2') // 图片
  const infinite = ref<boolean>(false)
  const isGoodsOnly = ref<boolean>(false)

  const baseList = ref([]) // 列表
  const existFile = ref<number>(9)
  const selectName = ref<string|number>('2') // 图片
  const selectBaseList = ref([])
  const selectNameStr = ref<any>('文本')
  const SOP = ref(false)
  const localUploadisShow= ref(['1', '2', '3', '4', '5', '6']) // 是否显示本地上传按钮 默认名单
  const disableUploadisShow = ref(['8', '27', '99'])    // 是否显示本地上传按钮 排除名单

  let tabItem = ref<any>()
    
  type SearchType = {
    article_title: string,
    official_account_id: string
  }
  let officialAccountsParams = reactive<SearchType>({
    article_title: '',
    official_account_id: '',
  })

  let officialAccountsParams_ = ref()
  
  let toggleType = ref<number>(0)

  let randomKey = ref<string>('')
  let randomKey2 = ref<string>('')

  let keyidaType = ref<string|number>('1')
  const types = ref<any>(['1', '4'])   // 1 客易达  2 有赞  3 淘宝  4 自营  5 线下门店

  let paginationData = reactive<any>(null)

  let showTabs = ref<any>([])
  let storesIds = ref<any>([])

  let multiple = ref<boolean>(true)

  //分组信息
  const treeData = ref([])
  const upInfo = () => {
    switch (baseId.value) {
      case '1': // 文本
        return {
          type: 0,
          upFile: [],
          limitSize: 2,
          limitNum: 1,
          multiple: true,
          acceptFile: '.txt'
        }
      break;
      case '2': //图片
        return {
          type: 1,
          upFile: [],
          limitSize: 2,
          limitNum: remainNum.value,
          multiple: true,
          acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
        }
      break;
      case '3': // 音频
        return {
          type: 4,
          upFile: [],
          limitSize: 200,
          limitNum: 1,
          multiple: false,
          acceptFile: '.mp3,.wma,.wav,.amr,.m4a'
        }
      break;
      case '4': // 视频
        return {
          type: 2,
          upFile: [],
          limitSize: 10,
          limitNum: 1,
          multiple: false,
          acceptFile: '.mp4'
        }
      break;
      case '5': // 文件
        return {
          type: 5,
          upFile: [],
          limitSize: 20,
          limitNum: 1,
          multiple: false,
          acceptFile: '.DOC,.DOCX,.XLS,.XLSX,.CSV,.PPT,.PPTX,.TXT,.PDF,.Xmind'
        }
      break;
      default:
        return {
          type: 1,
          upFile: [],
          limitSize: 2,
          limitNum: 1,
          multiple: true,
          acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
        }
      break;
    }
  }

  // tabs
  const tabs = ref([])

  const tabs2 = ref([
    { id: '2', type: 1, key: '1', name: '图片', nameStr: 'pic', total: 9, num: 0, comName: shallowRef(ImageList) },
    { id: '3', type: 4, key: '4', name: '音频', nameStr: 'audio', total: 9, num: 0, comName: shallowRef(AudioList) },
    { id: '4', type: 2, key: '2', name: '视频', nameStr: 'video', total: 9, num: 0, comName: shallowRef(VideoList) },
    { id: '5', type: 5, key: '5', name: '文件', nameStr: 'file', total: 9, num: 0, comName: shallowRef(FileList) },
    { id: '6', type: 3, key: '3', name: '链接', nameStr: 'link', total: 9, num: 0, comName: shallowRef(LinkList) },
    { id: '1', type: 0, key: '-1', name: '文本', nameStr: 'text', total: 1, num: 0, comName: shallowRef(TextList) },
    { id: '8', type: 6, key: '6', name: '抽奖', nameStr: 'luck', total: 9, num: 0, comName: shallowRef(LuckDraw) },
    { id: '27', type: 9, key: '6', name: '收集表', nameStr: 'collect', total: 9, num: 0, comName: shallowRef(CollectList) },
    { id: '99', type: 7, key: '9', name: '电商素材', nameStr: 'ecommerce', total: 9, num: 0, comName: null, GoodsList: shallowRef(GoodsList), PageList: shallowRef(PageList) },
    { id: '15', type: 10, key: '6', name: '公众号图文', nameStr: 'officialAccounts', total: 9, num: 0, comName: shallowRef(OfficialAccounts) }
  ])

  const getTabItem = (num?: string | number) => {
    const id = num || baseId.value
    selectNameStr.value = tabs.value.find((item: any) => item.id == id)?.name
  }

  const tabClick = async (val?: any) => {
    if(!!val){
      tabItem.value = tabs.value.find(item => item.id == baseId.value)
    }
    selctInfo.value = {
      type: 0,
      typeStr: '',
      data: []
    }
    getTabItem(val?.props.name)
    if(baseId.value != 15){
      await getGroupListData()
    }
    await getList()
  }

  const handleClose = () => {
    selectBaseList.value = []
    keyword.value = ''
    toggleType.value = 0
    materVisible.value = false
  }
  // 保存
  const submitHandel = () => {
    store.dispatch('table', {
      tableData: [],
      tableAll: false
    })
    if (selctInfo.value.data.length == 0) {
      ElMessage.error('请选择素材')
      return
    }
    handleClose()
    emit('submit', selctInfo.value)
  }

  const selectToggleType = async (type:number):void=>{
    keyword.value = ''
    toggleType.value = type
    selctInfo.value.data = []
    selectBaseList.value = []
    await getList()
  }

  const selctInfo = ref({
    type: 0,
    typeStr: 'text',
    data: []
  })
  // 选择数量
  const selectNum = computed(() => {
    if(baseId.value == 15){
      if(selctInfo.value?.data?.length){
        return Number(selctInfo.value.data[0].article_detail.length)
      }else{
        return Number(selctInfo.value.data.length)
      }
    }else{
      return Number(selctInfo.value.data.length)
    }
  })
  // 剩余数量
  const remainNum = computed(() => {
    if(existFile.value > selectNum.value){
      return Number(existFile.value - selectNum.value)
    }else{
      return 0
    }
  })
  // 素材库选的数据
  const getDataFun = (data: any) => {
    selctInfo.value = data
  }
  // 本地数据
  const getUploadFile = (data: any) => {
    // debugger
    if (data.type == 6) {
      data.local = true
      emit('submit', data)
    } else {
      const type = tabs2.value.find(item => item.id == baseId.value)?.type || '1'
      let params = {
        local: true,
        // type: baseId.value,
        type,
        data
      }
      emit('submit', params)
    }
    handleClose()
  }

  // 分组信息
  const getGroupListData = async () => {
    let res: any[] = [],
      defaultId = 0
    // 抽奖 分组
    if (baseId.value == 8) {
      res = await getGroupMarket({
        type: 13
      })
    } else if(baseId.value == 99){
      let data = await getMaterialStoreList({sub_num: 1})   // sub_num  1 可以获取到对应店铺商品的总数
      const total = data.length
      data = data.map(item=>{
        const {sub_num: sub_num = 0} = item
        item.name = `${item.name} (${item.sub_num || 0})`
        return item
      })
      res = {data, total}
    }else{
      res = await getGroupList({
        type: baseId.value
      })
    }
    let result: any[] = [
      {
        name: '全部分组',
        id: 'all',
        nums: 0,
        children: []
      }
    ]
    if (res.data.length > 0) {
      result[0].nums = res.total
      result[0].children = res.data
      defaultId = res.data[0].id
    }
    treeData.value = result
    groupId.value = defaultId
    shopId.value = defaultId
    
    selctInfo.value.data = []
    selectBaseList.value = []
    if(baseId.value == 99){
      if(!!storesIds.value?.length){
        const filterData = filteTreeData(res.data)
        treeData.value = filterData
        if(filterData?.length){
          groupId.value = filterData[0]?.id
          shopId.value = filterData[0]?.id
        }else{
          groupId.value = ''
          shopId.value = ''
        }
      }else{
        treeData.value = res.data
      }
      if(treeData.value?.length){
        shopType.value = treeData.value[0]?.type
      }else{
        shopType.value = ''
      }
    }

  }
  //  拿到分组的Id
  const getChildGroup = async (val: number) => {
    selctInfo.value.data = []
    selectBaseList.value = []
    groupId.value = val
    shopId.value = val
    shopType.value = treeData.value.find(ite=>ite.id == val)?.type || ''
    randomKey2.value = getRandomKey()
    toggleType.value = 0
    await getList()
  }
  const getList = async (data?: any) => {
    if(data?.page && data?.page_size) paginationData = data
    let params = {
      title: keyword.value,
      keyword: keyword.value,
      goods_info: keyword.value,
      page_name: keyword.value,
      group_id: groupId.value,
      shop_id: shopId.value,
      page: data?.page || paginationData?.page || 1,
      page_size: data?.page_size || paginationData?.page_size || 15
    }

    let result = [],
      res = null,
      type = Number(baseId.value)
    switch (type) {
      case 1: //文本
        res = await getTextList(params)
        break;
      case 2: //图片
        res = await getImageList(params)
        break;
      case 3: //语音
        res = await getVoiceList(params)
        break;
      case 4: // 视频
        res = await GetVideoList(params)
        break;
      case 5: // 文件
        res = await getFileList(params)
        break;
      case 6:
      case 7: // 链接
        res = await linkList(params)
        break;
      case 8: // 抽奖
        params.activity_status = 2
        res = await activityList(params)
        break;
      case 27: // 收集表
        params.type = 2
        res = await getCollectList(params)
        break;
      case 99: // 电商素材
        res = await getEcommerceList(params)
        break;
      case 15: // 公众号图文
        params.type = 2
        params.publish_state = 2   // 发布状态 0-全部 1-发布中 2-发布成功 3-发布失败
        params = Object.assign({}, params, officialAccountsParams)
        res = await getOfficialArticleList(params)
      break;
    }
    result = res?.data || []
    store.dispatch('pageTotal', res?.total || 0)
    baseList.value = []
    baseList.value = result
    baseList.value.forEach(item=>{
      item.isCheck = selectBaseList.value.some(ite => {
        if(ite.id == item.id && ite.tenant_id == item.tenant_id){
          ite.isCheck = true
          return true
        }else{
          return false
        }
      })
    })

    selectName.value = baseId.value
    randomKey.value = getRandomKey()
  }

  const filteTreeData = (arr:any):void=>{
    return arr.filter(item=>{
      return storesIds.value.includes(item.id)
    })
  }

  const getEcommerceList = async (params:any)=>{
    switch(toggleType.value){
      case 0:
        params.goods_status = 2
        params.stock_status = 1
        return await getGoodsList(params)
      break;
      case 1:
        params.page_status = 1
        return await getPageList(params)
      break;
    }
  }
  //本地上传
  const showCreatLocalLink = () => {
    CreateLocalLinkRef.value.showDialog()
  }
  //点击搜索框x号
  const clear = async () => {
    await getList()
  }

  const reset = async()=>{
    await getList()
  }

  const getRandomKey = (num?:number)=>{
    const t = "ABCDEFGHJKMNPQRSTWXYZ0123456789abcdefhijkmnprstwxyz?_*%$#";
    let total = "";
    let n = 0;
    if (typeof num === "number" && num > 0 && num < 21) {
        while (n < num) {
            const add = t[Math.round(Math.random() * Number(t.length - 1))];
            total = `${total}${add}`;
            n++;
        }
    } else {
        total = getRandomKey(16);
    }
    return total;
  }

  defineExpose({
    materVisible,
    baseId,
    existFile,
    showLuck,
    SOP,
    tabs,
    localUploadisShow,
    showTabs,
    multiple,
    storesIds,
    infinite,
    isGoodsOnly
  })

  watch(showTabs, (val:any)=>{
    if(val?.length){
      tabs.value = tabs2.value.filter((item:any) => val.includes(item.id))
    }
    tabClick()
  }, {deep: true, immediate: true})

  watch(baseId, (val:any)=>{
    if(!showTabs.value.includes(val)){
      baseId.value = showTabs.value[0]
    }
    tabItem.value = tabs.value.find(item => item.id == baseId.value)
  }, {immediate: true})

  
</script>

<style lang="scss">
  .mater_dialog {
    .el-dialog__header {
      padding: 0px;
    }
    .dialog_header {
      height: 50px;
      display: flex;
      padding-left: 20px;
      align-items: center;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #33302d;
      line-height: 16px;
      border-bottom: 1px solid #eaeaea;
    }
    .el-dialog__body {
      padding: 0;
    }
    .el-dialog__footer {
      border-top: 1px solid #eaeaea;
      // padding-top: 0;
    }
  }
</style>
<style lang="scss" scoped>
  .tab_box {
    min-height: 500px;
    // position: relative;
    .tab_header{
      width: 100%;
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 0 12px;
      position: relative;
      margin-bottom: 10px;

      &::after{
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background-color: #eee;
      }
      .base_tabs {
        width: 92%;
        // background: #f9f9f9;
        :deep .el-tabs__header{
          margin: 0;
          .el-tabs__nav-wrap{
            &::after{
              height: 0;
            }
          }
        }
        padding: 0 10px;
        box-sizing: border-box;

      }
      .tab_reset{
        width: 8%;
        text-align: center;
        white-space: nowrap;
        line-height: 38px;
        height: 38px;
        color: #FF6B00;
        // background: #f9f9f9;
        // border-bottom: 2px solid #E3E7ED;
        &:hover{
          cursor: pointer;
          color: #F99032;
        }
      }
    }
    
    .tab_content{
      display: flex;

      .group_box{
        width: 170px;
        max-height: 508px;
        background: #fff;
      }
      .line{
        width: 2px;
        background-color: #eee;
        margin: 0 0 8px 6px;
      }
      .pane-box{
        max-height: 508px;
        flex: 1;
        padding: 8px 16px 8px 16px;
        box-sizing: border-box;
        .pane-box-input{
          margin-bottom: 12px;
        }
        .pane-body-box {
          // margin-top: 12px;
          width: 100%;
          height: 404px;
          overflow-y: scroll;
          white-space: nowrap;
        }
        .pane-body-box-ecommerce{
          height: calc(404px - 54px);
        }
        .pane-body-box-public{
          height: calc(404px + 52px);
        }
        .pane-body-box::-webkit-scrollbar {
          width: 0 !important;
        }
        .pane-body-box::-webkit-scrollbar {
          width: 0 !important;
          height: 0;
        }
        :deep .el-pagination__sizes{
          margin-right: -10px;
        }
      }
    }
  }
  
  .footer_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row-reverse;
    .left_footer {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #33302d;
      span {
        color: #ff6b00;
        margin: 0 5px;
      }
      
    }
    .right_footer {
      display: flex;
      justify-content: flex-end;
    }
  }
  .ml20 {
    margin-left: 20px;
  }
</style>
